<template>
<section class="content" id="content">
  <el-row>
    <el-col>
      <el-button type="primary" @click="submitForm" v-if="optCase.operaCase !== 'view'">保存并上报</el-button>
<!--      <el-button type="warning" @click="()=>{}">编辑</el-button>-->
      <el-button type="danger" v-if="isDeleteBatch" @click="handleRemoveMaterial">批量删除</el-button>
      <el-button type="default" @click="closeDialog"  v-if="optCase.operaCase !== 'view'">取消</el-button>
      <el-button type="default" @click="handleReset"  v-if="optCase.operaCase !== 'view'">重置</el-button>
    </el-col>
  </el-row>
  <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
    <el-tab-pane label="重大危险源信息" name="tab1">
      <major-hazard-base-info ref="baseInfoRef"></major-hazard-base-info>
    </el-tab-pane>
    <el-tab-pane label="危险物质列表" name="tab2">
      <component ref="hazardMaterialRef"
                 :is="activeName==='tab2' ? MajorHazardMaterial : 'span'"
                 @showDelBatchBtn="showDelBatchBtn">
      </component>
    </el-tab-pane>
    <el-tab-pane label="备案申请表" name="tab3">
      <major-hazard-register-info ref="registerInfoRef"></major-hazard-register-info>
    </el-tab-pane>
    <el-tab-pane label="备案材料清单" name="tab4">
      <component :is="activeName==='tab4' ? MajorHazardRegisterFile : 'span'"></component>
    </el-tab-pane>
    <el-tab-pane label="历次申请记录" name="tab5">
      <component :is="activeName==='tab5' ? HistoryRegisterRecord : 'span'"></component>
    </el-tab-pane>
    <el-tab-pane label="流程查看" name="tab6">
      <component :is="activeName==='tab6' ? MajorHazardRegisterRecord : 'span'"></component>
    </el-tab-pane>
  </el-tabs>
</section>
</template>

<script setup lang="ts">/**
 * 全局方法引入
 */
const global = getCurrentInstance().appContext.config.globalProperties;

import {
  ref,
  reactive,
  onMounted,
  toValue,
  defineExpose,
  defineEmits,
  getCurrentInstance,
  inject, nextTick, provide,
} from "vue";
import {
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules
} from "element-plus";
import type { TabsPaneContext } from 'element-plus'
import {
  closeDialogKey,
  editKey,
  registerFileIdKey,
  removeFileParamKey
} from '../../components/keys.js';
// import lqtableCommon from '../../components/lqtableCommon.js';
import MajorHazardBaseInfo from '@/pages/ent/majorHazard/MajorHazardBaseInfo.vue'
import MajorHazardMaterial from '@/pages/ent/majorHazard/MajorHazardMaterial.vue'
import MajorHazardRegisterInfo from '@/pages/ent/majorHazard/MajorHazardRegisterInfo.vue'
import MajorHazardRegisterFile from '@/pages/ent/majorHazard/MajorHazardRegisterFile.vue'
import HistoryRegisterRecord from '@/pages/ent/majorHazard/HistoryRegisterRecord.vue'
import MajorHazardRegisterRecord from '@/pages/ent/majorHazard/MajorHazardRegisterRecord.vue'

const optCase = inject(editKey);
const closeDialog = inject(closeDialogKey);

const activeName = ref('tab1');
//重大危险源信息
const baseInfoRef = ref<FormInstance>();
//危险物质列表
const hazardMaterialRef = ref();
//备案申请表
const registerInfoRef = ref<FormInstance>();

//备案材料清单

//历次申请记录

//流程查看

const emit = defineEmits<{
  (e: 'changeTitle', value: Object): void
}>()

const handleClick = (tab: TabsPaneContext, event: Event) => {
  // console.log(tab, event)
  emit('changeTitle',{title: tab.props.label});
  switch (activeName.value) {
    case 'tab2':
      // return MajorHazardMaterial
  }
}

//保存并上报,提交所有表单
const submitForm = async () => {
  let warning = '';
  let valid = true;
  await baseInfoRef.value?.handleSubmit().then(resp => {
    if (!resp) {
      valid = resp;
      warning += `【重大危险源信息】标签页信息未正确填写！<br/>`;
    }
  });
  await registerInfoRef.value?.handleSubmit().then(resp => {
    // console.log(`验证 备案申请表: `, resp);
    valid = valid && resp;
    if (!resp) {
      warning += `【备案申请表】标签页信息未正确填写！`;
    }
  });
  //验证通过
  if (!valid) {
    ElMessage({
      dangerouslyUseHTMLString: true,
      type: "warning",
      message: warning}
    );
    if (warning.includes('重大危险源信息')) {
      activeName.value = 'tab1';
    } else {
      activeName.value = 'tab3';
    }
  } else {
    console.log('执行重大危险源信息新增操作！');
    if (optCase.value.operaCase === 'add') {
      global.$api.insertMajorHazard(
          Object.assign({},
              {
                basicInfo: {...baseInfoRef.value?.getModel()},
                registerInfo: {...registerInfoRef.value?.getModel()}
              })
      ).then(({ data }) => {
        if (data.status === 'OK') {
          //新增成功两表单为只读不可修改
          baseInfoRef.value?.disableForm();
          registerInfoRef.value?.disableForm();
          //新增成功后共享相关id，新增 “危险物质” “备案材料清单” 等需要
          optCase.value.id = data.data.id;
          optCase.value.hazardInfoId = data.data.id;
          optCase.value.hazardCode = data.data.hazardCode;
          ElMessage({
            dangerouslyUseHTMLString: true,
            type: "success",
            message: '您已经成功新增【重大危险源信息】和 【备案申请表】！<br/><br/>请继续新增【危险物质】和 上传【备案材料】。',
            duration: 4000
          });
          //却换到【危险物质列表】标签页，新增危险物质
          activeName.value = 'tab2';
          optCase.optStatus = true;
        }
      });

    } else if(optCase.value.operaCase === 'edit') {
      /*重大危险源标识不变*/
      global.$api.dumpMajorHazard(
          Object.assign({},
              {
                basicInfo: {...baseInfoRef.value?.getModel()},
                registerInfo: {...registerInfoRef.value?.getModel()}
              })
      ).then(({ data }) => {
        if (data.status === 'OK') {
          optCase.value.id = data.data.id;
          optCase.value.hazardInfoId = data.data.id;

          //新增成功两表单为只读不可修改
          baseInfoRef.value?.disableForm();
          registerInfoRef.value?.disableForm();
          ElMessage({
            dangerouslyUseHTMLString: true,
            type: "success",
            message: '您已经成功更新相关信息；系统仍保留原有旧信息！',
            duration: 5000
          });
          optCase.optStatus = true;

        } else {
          ElMessage({
            dangerouslyUseHTMLString: true,
            type: "error",
            message: '您重新上报相关数据失败；原有数据未受影响！',
            duration: 6000
          });
        }
      });
    }
  }
}

//重置表单并清理验证信息
const handleReset = () => {
  switch (activeName.value) {
    case 'tab1': baseInfoRef.value?.handleReset();
    case 'tab3': registerInfoRef.value?.handleReset();
  }
}

const resetFirstTab = async () => activeName.value = 'tab1';

//危险物质列表多选时显示指删除按键
const isDeleteBatch = ref(false);

const showDelBatchBtn = (flag) => {
  isDeleteBatch.value = flag;
}
//指量删除危险物质
const handleRemoveMaterial = () => {
  hazardMaterialRef.value?.deleteBatch();
}

defineExpose({
  handleReset,
  resetFirstTab
})

//预生成的备案材料id
const registerFileId = ref('');
provide(registerFileIdKey, registerFileId);

const removeFileParam = ref({
  applicationForm: {id: '', registerFileId: '', key: ''},
  gradedRecord: {id: '', registerFileId: '', key: ''},
  basicFeature: {id: '', registerFileId: '', key: ''},
  technicalManual: {id: '', registerFileId: '', key: ''},
  layoutDevice: {id: '', registerFileId: '', key: ''},
  opRules: {id: '', registerFileId: '', key: ''},
  testResult: {id: '', registerFileId: '', key: ''},
  planReport: {id: '', registerFileId: '', key: ''},
  safetyReport: {id: '', registerFileId: '', key: ''},
  warningSign: {id: '', registerFileId: '', key: ''},
  keyDevice: {id: '', registerFileId: '', key: ''},
  etc: {id: '', registerFileId: '', key: ''},
})
provide(removeFileParamKey, removeFileParam);


onMounted(()=>{
  if (optCase.value.operaCase === 'add') {
      global.$api.generateIdForRegisterFile({}).then(({data}) => {
        registerFileId.value = data.data.id;
        console.log('Add 时预生成的 备案材料id:%s', registerFileId.value);
      })
  } else {

  }
});

</script>

<style scoped>

</style>
